package com.cqndt.disaster.device.common.shrio;

import org.apache.shiro.authc.*;
import org.apache.shiro.util.ByteSource;
import com.cqndt.disaster.device.vo.TabUserVo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.authz.AuthorizationInfo;
import org.springframework.stereotype.Component;
import com.cqndt.disaster.device.dao.TabUserMapper;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

/**
 * @author lgb
 * @date 2020-8-26
 * @说明 权限、登录认证
 **/
@Component
public class UserRealm extends AuthorizingRealm{

    @Autowired
    private TabUserMapper tabUserMapper;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	/**
	 * @param authcToken
	 * @return 认证(登录时调用)
	 **/
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException{
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
		//查询用户信息
		TabUserVo user = new TabUserVo();
		user.setUserName(token.getUsername());
		user = tabUserMapper.getUserByUserName(user);
		//账号不存在
		if(user == null) {
			throw new UnknownAccountException("账号不存在");
		}
		//账号锁定
		if("0".equals(user.getStatus())){
			throw new LockedAccountException("账号已被禁用,请联系管理员");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
		return info;
	}

	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
		shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
		shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
		super.setCredentialsMatcher(shaCredentialsMatcher);
	}
}